<?php

namespace app\data\controller\api;

use app\data\service\UserService;
use think\admin\Controller;
use think\facade\Db;

require_once VENDOR_PATH . 'WxDecode/wxBizDataCrypt.php';
require_once VENDOR_PATH . 'WxDecode/errorCode.php';

/**
 * 会员登录注册接口
 * Class Login
 * @package app\data\controller\api
 */
class Login extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'DataMember';


    /**
     * 会员登录接口
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function in()
    {
        /*$data = $this->_vali([
            'phone.mobile'     => '手机号码格式错误！',
            'phone.require'    => '手机号码不能为空！',
            'password.require' => '登录密码不能为空！',
        ]);*/
        $params = input();
        $data = [
            'phone'     => $params['phone'],
            'phonecode' => $params['phonecode']
        ];

        //获取微信用户信息
        $rawData = json_decode($params['rawData']);
        $data['username'] = $rawData->{'nickName'};
        $data['region_city'] = $rawData->{'city'};
        $data['region_province'] = $rawData->{'province'};
        $data['headimg'] = $rawData->{'avatarUrl'};

        if (isset($params['code'])) {
            $api = "https://api.weixin.qq.com/sns/jscode2session";
            //发送
            $str_json = $this->httpGet($api . '?appid=' . $this->appid . '&secret=' . $this->appsecret . '&js_code=' . $params['code'] . "&grant_type=authorization_code");
            $str = json_decode($str_json, true);
            if (!empty($str['errcode']) || empty($str['openid'])) {
                $this->error('获取openid失败，请删除小程序重试', $str);
            }else{
                $data['openid1'] = $str['openid'];
                $map = ['deleted' => 0, 'openid1' => $data['openid1']];
                $code = $data['phonecode'];
                $user = $this->app->db->name($this->table)->where($map)->find();
                if (!empty($user)){
                    if (empty($user['status'])) $this->error('该会员账号状态异常！');
                }else{
                    unset($data['phonecode']);
                    UserService::instance()->save($map,$data,true);
                }
                if (!empty($code)) {
                    $this->success('手机登录成功！', UserService::instance()->get($map, true));
                } else {
                    $this->error('账号登录失败，请稍候再试！');
                }
            }
        }else{
            $this->error('参数缺失');
        }
    }

    /**
     * 会员统一注册入口
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function register()
    {
        /*$data = $this->_vali([
            'username.default'        => '',
            'region_area.default'     => '',
            'region_city.default'     => '',
            'region_province.default' => '',
            'phone.mobile'            => '手机号码格式错误！',
            'phone.require'           => '手机号码不能为空！',
            'password.require'        => '登录密码不能为空！',
        ]);*/
        $data = input('post.');
        $map = ['phone' => $data['phone'], 'deleted' => 0];
        if ($this->app->db->name($this->table)->where($map)->count() > 0) {
            $this->error('手机号已注册，请使用其它手机号！');
        }
        $data['password'] = md5($data['password']);
        $user = UserService::instance()->save($map, $data, true);
        empty($user) ? $this->success('会员注册成功！', $user) : $this->error('手机注册失败！');
    }

    /**
     * 发送验证码
     */
    public function sendSms(){
        /*$data = $this->_vali([
            'phone.require'     => '请输入手机号'
        ]);*/
        $data = input('post.');
        $code = rand(1000,9999);
//        $res = tencentSms($data['phone'],$code);
        $res = 1;
        if ($res){
            $this->success('发送成功',$code);
        }else{
            $this->error('发送失败');
        }
    }

    public function demo(){
        dump(input());
        $data = $this->_vali([
            'phone.require'     => '请输入手机号'
        ]);
    }


    function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    public function wxDecode(){
        // 接收参数
        $data = request() -> param();
        $appid = sysconf('wxapp_appid');
        $appsecret = sysconf('wxapp_appkey');
        $grant_type = "authorization_code";
        $code = $data['code'];
        $encryptedData=$data['encryptedData'];
        $iv = $data['iv'];
        $signature = $data['signature'];
        $rawData = $data['rawData'];
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);
        $sessionKey = $res['session_key']; //取出json里对应的值
        $signature2 = sha1(htmlspecialchars_decode($rawData).$sessionKey);
        // 验证签名
        if ($signature2 !== $signature){
            return json("验签失败");
        }
        // 获取解密后的数据
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            return json($data);
        } else {
            $this->error('登录失败');
        }
    }

    public function login(){
        $params = $this->request->post();
        if (isset($params['code'])) {
            $appid = sysconf('wxapp_appid');
            $secret = sysconf('wxapp_appkey');
            $api = "https://api.weixin.qq.com/sns/jscode2session";

            //发送
            $str_json = $this->httpGet($api,['appid'=>$appid,'secret'=>$secret,'js_code'=>$params['code'],'grant_type'=>'authorization_code']);
            $str = json_decode($str_json,true);
            if(!empty($str['errcode']) || empty($str['openid'])){
                $this->error('获取openid失败，请删除小程序重试',$str);
            }else{
                $user = Db::name("member")->where('openid',$str['openid'])->find();
                if(!$user){
                    $user['id'] = Db::name("member")->insertGetId(['openid'=>$str['openid'],'avatar_image'=>'/uploads/defalt_avatar/male.png','status'=>'normal']);
                }
                $this->success('获取成功',$str);
            }
        }else{
            return $this->error('参数缺失');
        }
    }


    public function getUserNumber(){
        $params = input('post.');

        $appid = sysconf('wxapp_appid');
        $sesson_key = $params['session_key'];
        // 解密，查看官方给的示例文件
        $pc = new WXBizDataCrypt($appid,$sesson_key);
        $encryptedData = $params['encryptedDataStr'];
        $iv = $params['iv'];
        $pc->decryptData($encryptedData, $iv, $encryptedData);
        $decode_data = json_decode($decode_data,true);
        if(!empty($decode_data['purePhoneNumber'])){
            $user = Db::name("member")->where('openid',$params['openid'])->find();
            if(!$user){
                $this->error("用户不存在");
            }else{
                if(!empty($user['mobile'])){
                    if($user['mobile'] != $decode_data['purePhoneNumber']){
                        $this->error('此微信已经被其它手机号绑定');
                    }
                }else{
                    Db::name('user')->where('id',$user['id'])->update([
                        'mobile'=>$decode_data['purePhoneNumber'],
                        'avatar_image'=>'/uploads/defalt_avatar/male.png'
                    ]);
                }
            }
            $ret = $this->auth->direct($user['id']);
            if($ret){
                $this->success('登录成功',['userInfo'=>$this->auth->getUserinfo()]);
            }else{
                $this->error('登录失败');
            }
        }else{
            $this->error('微信登录过期，请删除小程序重新打开',['type'=>'decodeErr',$decode_data,$params]);
        }
    }

}